<template>
  <el-dialog
    :visible.sync="resourceVisible"
    :before-close="handleClose"
    :append-to-body="true"
    :lock-scroll="true"
    :class="{ 'supplier-resource-list-mobile-dialog': showMobilePage }"
    class="suplier-resource-list large-common-dialog-size">
    <div class="resource-title">
      <Title :title="'资源管理列表'" font-size="16px" style="flex: 1;"/>
      <div v-if="!showMobilePage" class="list-tab-relative">
        <div class="list-tab-absolute">
          <ListTab v-model="tabIndex" :tabs="tabs" :is-center="true" padding-left="0px" @tabClick="tabClick"/>
        </div>
      </div>
    </div>
    <div v-if="showMobilePage" class="list-tab-relative">
      <div class="list-tab-absolute">
        <ListTab v-model="tabIndex" :tabs="tabs" :is-center="true" padding-left="0px" @tabClick="tabClick"/>
      </div>
    </div>
    <div>
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <el-form :model="queryForm" inline style="flex: 1">
          <el-form-item label="资源搜索" style="margin-bottom:12px">
            <el-input v-model.trim="queryForm.resourceName" size="small" placeholder="请输入资源账号名称关键词" style="width: 240px" @keyuo.native.enter="getList"/>
          </el-form-item>
          <el-form-item style="margin-bottom:12px">
            <el-button class="search-btn-style" plain type="primary" size="small" @click="toSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        v-loading="listLoading"
        v-if="list.total > 0"
        :data="list.items"
        :header-cell-style="{color: '#141C3D'}"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        max-height="300"
        height="300"
        fit
        hightlight-current-row
        class="fb-table">
        <el-table-column align="left" label="账号" width="150">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.resource" placement="top-start" effect="dark">
              <div slot="content">
                {{ scope.row.resource || '--' }}
              </div>
              <div>{{ scope.row.resource || '--' }}</div>
            </el-tooltip>
            <div v-else>{{ scope.row.resource || '--' }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="链接" width="120">
          <template slot-scope="scope">
            <ToolTip v-if="scope.row.link" :content="scope.row.link" />
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="平台" width="110">
          <template slot-scope="scope">
            <div class="flex-center">
              <platformIcon :data="scope.row.platform" />
              {{ scope.row.platform || '--' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="所属机构" width="90">
          <template slot-scope="scope">
            <ToolTip v-if="scope.row.organization" :content="scope.row.organization" />
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="执行人" width="100">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.operator && scope.row.operator.length" class="item" placement="top-start" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.operator.join('/') }}</div>
              <div class="resource-name ellipsis">{{ scope.row.operator.join('/') }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <el-table-column :fixed="showMobilePage && 'right'" :width="showMobilePage ? '60' : '100'" align="left" label="操作">
          <template slot-scope="scope">
            <div>
              <el-button v-if="!resourceType" :disabled="!hasRouteAuth('medium:supplier:resourceEdit') || scope.row.isChoice" type="text" size="small" @click="choice(scope)">
                {{ scope.row.isChoice ? '已选择' : '选择' }}
              </el-button>
              <el-button v-else :disabled="!hasRouteAuth('medium:supplier:resourceEdit')" type="text" size="small" @click="del(scope)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <empty-placeholder v-else :empty-img="emptyTableDataImg" image-size="120px" style="margin-bottom: 24px;height:324px"/>
      <el-row type="flex" justify="end" class="pagination-area">
        <el-pagination
          v-if="!showMobilePage"
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-pagination
          v-else
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
  </el-dialog>
</template>
<script>
import axios from 'axios';// 取消未完成请求
import { resourceList, resourceChoice, resourceDel, resourceChoiceRepeat } from '@/api/supplier';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import platformIcon from '@/components/Common/platformIcon';
import ListTab from '@/components/ListTab';
import { hasRouteAuth } from '@/utils/permission';
import emptyTableDataImg from '@/assets/empty-table-data.png';
// import setting from '@/assets/setting.png';
export default {
  components: { Title, EmptyPlaceholder, platformIcon, ListTab },
  props: {
    id: {
      type: Number,
      default: null
    },
    resourceVisible: {
      type: Boolean,
      default: false
    },
    resourceGroupId: { // 资源组ID
      type: Number,
      default: null
    },
    resourceType: {
      type: Number,
      default: 0
    },
    showMobilePage: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      emptyTableDataImg,
      // setting,
      params: {
        page: 1,
        perPage: 20
      },
      queryForm: {
        resourceName: ''
      },
      listLoading: false,
      list: {},
      isChoice: false,
      tabIndex: 0,
      tabs: [{
        'id': 0,
        'name': '添加资源',
        'num': 0
      }, {
        'id': 1,
        'name': '关联列表',
        'num': 0
      }]
    };
  },
  watch: {
    resourceVisible(newV, oldV) {
      if (newV) {
        this.getList();
      }
    },
    resourceType: {
      handler(newV, oldV) {
        this.tabIndex = newV;
      },
      immediate: true
    }
  },
  methods: {
    hasRouteAuth,
    getList(toPage = 1) {
      this.listLoading = true;
      this.params.page = toPage;
      const params = {
        ...this.params,
        ...this.queryForm,
        id: this.resourceGroupId,
        type: this.resourceType
      };
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      resourceList(params, source.token).then(res => {
        res.data.items.map(item => {
          item.isChoice = false;
          // item.operatorName = item.operator.map(j => j.value);
          return item;
        });
        this.list = res.data;
        this.listLoading = false;
      }).catch(err => {
        this.listLoading = false;
        console.error(err);
      });
    },
    tabClick(val) {
      this.queryForm = {};
      this.$emit('changeType', val);
      setTimeout(() => {
        this.getList();
      });
    },
    handleClose() {
      this.queryForm = {};
      this.$emit('resourceDialog', false);
    },
    toSearch() {
      this.getList();
    },
    // 选择关联资源
    relateResource(params) {
      resourceChoice(params).then(res => {
        this.$message.success('选择成功');
        this.$emit('updateData'); // 刷新整个资源详情
      }).catch(err => {
        console.error(err);
      });
    },
    choice(scope) {
      // 判断关联的资源是否重复关联
      const params = {
        id: scope.row.id,
        supplierId: this.id,
        resourceGroupId: this.resourceGroupId
      };
      resourceChoiceRepeat(params).then(res => {
        const resourceParams = {
          id: scope.row.id,
          resourceGroupId: this.resourceGroupId
        };
        if (res.code === 501) {
          this.$confirm(res.message, '', {
            confirmButtonText: '确定',
            cancelButtonText: '再想想',
            type: 'warning',
            showClose: false,
            center: true,
            iconClass: 'charge-icon',
            customClass: 'del-message del-message-cancel'
          }).then(() => {
            scope.row.isChoice = true;
            this.relateResource(resourceParams);
          }).catch(() => {
            scope.row.isChoice = false;
            return false;
          });
        } else {
          scope.row.isChoice = true;
          this.relateResource(resourceParams);
        }
      });
    },
    // END
    del(scope) {
      this.$confirm('确认取消当前关联资源账号？', '', {
        confirmButtonText: '确认',
        cancelButtonText: '再想想',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        resourceDel(scope.row.id).then(res => {
          this.$message.success('删除成功');
          this.getList(this.list.page);
          this.$emit('updateData'); // 刷新整个资源详情、
        });
      });
    },
    handleSizeChange(page) {
      this.params.perPage = page;
      this.getList();
    },
    handleCurrentChange(toPage) {
      this.getList(toPage);
    }
  }
};
</script>
<style lang="scss">
.suplier-resource-list {
    .el-dialog__body{
      padding-bottom: 6px !important;
    }
  .resource-title {
    margin-bottom: 12px;
    .list-tab-relative {
      position: relative;
      height: 18px;
      .list-tab-absolute {
        position: absolute;
        top: -30px;
        left: 50%;
        transform: translateX(-50%);
      }
    }
  }
}
.supplier-resource-list-mobile-dialog {
  .el-dialog {
    width: 100% !important;
    .el-pagination {
      overflow-x: auto;
    }
  }
}
</style>
